package com.atguigu.cloud.controller;

import com.atguigu.cloud.entities.PayDTO;
import com.atguigu.cloud.resp.ResultData;
import jakarta.annotation.Resource;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @className: OrderController
 * @author: 刘远鑫
 * @date: 2024/3/4
 **/

@RestController
@RequestMapping("/order")
public class OrderController {

//    public static final String PaymentSrv_URL = "http://localhost:8001";
    public static final String PaymentSrv_URL = "http://cloud-payment-service";

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/pay/add")
    public ResultData addOrder(PayDTO payDTO) {
        return restTemplate.postForObject(PaymentSrv_URL + "/pay/add", payDTO, ResultData.class);
    }

    @GetMapping("/pay/delete/{id}")
    public void deletePay(@PathVariable("id") Integer id) {
         restTemplate.delete(PaymentSrv_URL + "/pay/delete/"+id, id, ResultData.class);
    }

    @GetMapping("/pay/update")
    public void updatePay(PayDTO payDTO) {
        restTemplate.put(PaymentSrv_URL + "/pay/update", payDTO, ResultData.class);
    }
    @GetMapping("/pay/getById/{id}")
    public ResultData getPayInfo(@PathVariable("id") Integer id) {
        return restTemplate.getForObject(PaymentSrv_URL + "/pay/getById/" + id, ResultData.class, id);
    }

    @GetMapping("/pay/getAll")
    public ResultData getPayAll() {
        return restTemplate.getForObject(PaymentSrv_URL + "/pay/getAll", ResultData.class);
    }

    @GetMapping("/pay/getInfoByConsul")
    public String getInfoByConsul() {
        return restTemplate.getForObject(PaymentSrv_URL + "/pay/getInfoByConsul", String.class);
    }

    @Resource
    private DiscoveryClient discoveryClient;
    @GetMapping("/discoveryClient")
    public ServiceInstance discoveryClient() {
        for (String service : discoveryClient.getServices()) {
            System.out.println(service);
        }
        final List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        for (ServiceInstance instance :instances ) {
            System.out.println(instance.getHost()+instance.getPort()+instance.getUri());
        }
        return  instances.get(0);
    }


}
